﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EWms.Core.Components
{
    public static class SwaggerSetup
    {
        public static readonly Dictionary<string, OpenApiInfo> ApiDocs = new Dictionary<string, OpenApiInfo>()
        {
            {"v1",new OpenApiInfo(){Title="EWms.WebApi",Description="EWms.WebApi",Version="v1"}}
        };
        /// <summary>
        /// 配置Swagger
        /// </summary>
        /// <param name="services"></param>
        public static void AddSwagger(this IServiceCollection services)
        {
            services.AddEndpointsApiExplorer();
            services.AddSwaggerGen(c =>
            {
                foreach (var doc in ApiDocs)
                {
                    c.SwaggerDoc(doc.Key, doc.Value);
                }
                #region 在SwaggerUI上添加授权
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" }
                        },
                        new List<string>()
                    }
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可，注意两者之间有空格",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer",
                    BearerFormat = "JWT"
                });
                #endregion

                var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath, true);
            });
        }
        /// <summary>
        /// 配置Swagger
        /// </summary>
        /// <param name="app"></param>
        public static void AddSwagger(this IApplicationBuilder app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                foreach (var doc in ApiDocs)
                {
                    c.SwaggerEndpoint($"/swagger/{doc.Key}/swagger.json", doc.Value.Title);
                }
                c.DocExpansion(DocExpansion.List);
                c.DefaultModelsExpandDepth(-1); //swagger 不显示Model
            });
        }
    }
}
